# -*- coding:utf-8 -*-
# #安装OPEN-CV
# pip install --upgrade setuptools
# pip install numpy Matplotlib
# pip install opencv-python
import subprocess

import pytesseract
import requests

from PIL import Image,ImageEnhance
from PIL.ImageShow import show

import cv2 as cv
def edit_resize(img,i):
    imgInfo = img.shape
    print(imgInfo)  # 输出的三个数据为高度，宽度，模式，模式为3即一个像素点由三种颜色组成
    height = imgInfo[0]
    width = imgInfo[1]
    mode = imgInfo[2]
    # 1 放大 缩小2 等比例 非等比例
    dstHeight = int(height * i)  # 高度变为0.2倍
    dstWidth = int(width * i)  # 宽度变为0.2倍
    img = cv.resize(img, (dstWidth, dstHeight))  # 双线性插值（下次介绍）
    return img


def download(num):
    url = 'http://www.stdol.com/e/ShowKey/?v=reg&t=0.012641020017994276'

    for i in range(200):
        num = int(i)
        img = requests.get(url)
        with open(f'imgs\\{num}.jpg', 'wb') as f:
            f.write(img.content)
        img = cv.imread(f'imgs\\{num}.jpg')  # 读取图片对象
        img = edit_resize(img, 5)
        cv.imwrite(f'imgs\\{num}.jpg', img)  # 保存图像到:H:\\img

# download(200)
# im = Image.open('imgs/1.jpg')
# print(pytesseract.image_to_string(im, lang='eng'))

#二值化图像传入图像和阈值
def binarizing(img,threshold):
    """传入image对象进行灰度、二值处理"""
    img = img.convert("L")# 转灰度
    pixdata = img.load()
    w, h = img.size
    #  遍历所有像素，大于阈值的为黑色
    for y in range(h):
        for x in range(w):
            if pixdata[x, y] < threshold:
                pixdata[x, y] = 255
            else:
                pixdata[x, y] = 0
    return img


#降噪
def depoint(img):
    """传入二值化后的图片进行降噪"""
    pixdata = img.load()
    w,h = img.size
    for y in range(1,h-1):
        for x in range(1,w-1):
            count = 0
            if pixdata[x,y-1] > 245:#上
                count = count + 1
            if pixdata[x,y+1] > 245:#下
                 count = count + 1
            if pixdata[x-1,y] > 245:#左
                 count = count + 1
            if pixdata[x+1,y] > 245:#右
                 count = count + 1
            if pixdata[x-1,y-1] > 245:#左上
                 count = count + 1
            if pixdata[x-1,y+1] > 245:#左下
                 count = count + 1
            if pixdata[x+1,y-1] > 245:#右上
                 count = count + 1
            if pixdata[x+1,y+1] > 245:#右下
                 count = count + 1
            if count > 4:
                pixdata[x,y] = 255
        return img



